<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800PX" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="auto">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="车间" prop="deptId">
              <treeselect v-model="formData.deptId" :options="deptList" :normalizer="normalizer" placeholder="选择所属车间"
                style="width: 100%" :disabled="!!formData.id" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品" prop="productId">
              <el-select v-model="formData.productId" placeholder="请输入产品名称进行搜索" filterable style="width: 100%" remote
                :remote-method="productRemoteMethod" :loading="productLoading" @change="handleProductChange" :disabled="!!formData.id">
                <el-option v-for="product in productList" :key="product.id" :label="product.productName"
                  :value="product.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工艺路线" prop="processRouteId">
              <el-select v-model="formData.processRouteId" placeholder="请输入工艺路线名称进行搜索" filterable style="width: 100%"
                remote :remote-method="processRouteRemoteMethod" :loading="processRouteLoading"
                @change="handleProcessRouteChange">
                <el-option v-for="route in processRouteList" :key="route.id" :label="route.processRouteName"
                  :value="route.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划开始时间" prop="planBeginTime">
              <el-date-picker clearable v-model="formData.planBeginTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择计划开始时间" style="width: 100%" :disabled="!!formData.id" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划结束时间" prop="planEndTime">
              <el-date-picker clearable v-model="formData.planEndTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择计划结束时间" style="width: 100%" :disabled="!!formData.id" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划数量" prop="planQuantity">
              <el-input v-model="formData.planQuantity" placeholder="请输入计划数量" style="width: 100%" :disabled="!!formData.id" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否良率计算" prop="yield">
              <el-switch v-model="formData.yield" active-value="true" inactive-value="false" :disabled="!!formData.id" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as PlanApi from '@/api/production/plan';
import * as ProductApi from '@/api/basic/product';
import * as ProcessRouteApi from '@/api/basic/processroute';
import { listDept } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "PlanForm",
  components: {
    Treeselect
  },
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        deptId: undefined,
        productId: undefined,
        processRouteId: undefined,
        planBeginTime: undefined,
        planEndTime: undefined,
        planQuantity: undefined,
        yield: false,
      },
      // 部门列表
      deptList: [],
      // 产品列表
      productList: [],
      // 产品加载状态
      productLoading: false,
      // 工艺路线列表
      processRouteList: [],
      // 工艺路线加载状态
      processRouteLoading: false,
      // 表单校验
      formRules: {
        deptId: [{ required: true, message: '车间Id不能为空', trigger: 'blur' }],
        productId: [{ required: true, message: '产品Id不能为空', trigger: 'blur' }],
        processRouteId: [{ required: true, message: '工艺路线Id不能为空', trigger: 'blur' }],
        planBeginTime: [{ required: true, message: '计划开始时间不能为空', trigger: 'blur' }],
        planEndTime: [{ required: true, message: '计划结束时间不能为空', trigger: 'blur' }],
        planQuantity: [{ required: true, message: '计划数量不能为空', trigger: 'blur' }],
      },
    };
  },
  methods: {
    normalizer(node) {
      // 构建基础对象，确保包含 id, label, children 属性
      return {
        id: node.id,
        label: node.name,
        children: node.children, // 必须包含 children
      };
    },

    /** 获取部门列表 */
    async getDeptList() {
      try {
        const response = await listDept();
        this.deptList = this.handleTree(response.data, "id")[0].children;
      } catch (error) {
        console.error('获取部门列表失败', error);
      }
    },

    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      // 加载部门列表
      await this.getDeptList();
      // 修改时，设置数据
      if (id) {
        this.dialogTitle = "配置工艺路线";
        this.formLoading = true;
        try {
          const res = await PlanApi.getPlan(id);
          this.formData = res.data;
          // 如果有产品ID，需要显示对应的产品名称
          if (this.formData.productId) {
            await this.productRemoteMethod('');
          }
          // 如果有工艺路线ID，需要显示对应的工艺路线名称
          if (this.formData.processRouteId) {
            await this.processRouteRemoteMethod('');
          }
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增生产计划";
        await this.productRemoteMethod('');
        await this.processRouteRemoteMethod('');
      }
    },

    /** 产品远程搜索方法 */
    async productRemoteMethod(query) {
      this.productLoading = true;
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          productName: query,
        };
        const response = await ProductApi.getProductPage(params);
        this.productList = response.data.list;
      } catch (error) {
        console.error('搜索产品失败', error);
        this.productList = [];
      } finally {
        this.productLoading = false;
      }
    },

    /** 处理产品选择 */
    handleProductChange(productId) {
      const selectedProduct = this.productList.find(product => product.id === productId);
      if (selectedProduct) {
        // 可以在这里同步产品名称到表单
        // this.formData.productName = selectedProduct.productName;
      }
    },

    /** 工艺路线远程搜索方法 */
    async processRouteRemoteMethod(query) {
      this.processRouteLoading = true;
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          processRouteName: query,
        };
        const response = await ProcessRouteApi.getProcessRoutePage(params);
        this.processRouteList = response.data.list;
      } catch (error) {
        console.error('搜索工艺路线失败', error);
        this.processRouteList = [];
      } finally {
        this.processRouteLoading = false;
      }
    },

    /** 处理工艺路线选择 */
    handleProcessRouteChange(processRouteId) {
      const selectedRoute = this.processRouteList.find(route => route.id === processRouteId);
      if (selectedRoute) {
        // 可以在这里同步工艺路线名称到表单
        // this.formData.processRouteName = selectedRoute.processRouteName;
      }
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await PlanApi.updatePlan(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await PlanApi.createPlan(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        deptId: undefined,
        productId: undefined,
        processRouteId: undefined,
        planBeginTime: undefined,
        planEndTime: undefined,
        planQuantity: undefined,
        yield: false
      };
      this.resetForm("formRef");
    }
  }
};
</script>
